package com.itwn.portal.web;

import com.itwn.portal.entity.Report;
import com.itwn.portal.reult.ResponseResult;
import com.itwn.portal.service.ReportService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.Date;

/**
 * @author cx
 * @date 2022/3/2
 * @apiNote
 */
@RestController
@RequestMapping("report")
public class ReportController {
    @Value("${imgReportPath}")
    String imgReportPath;
    @Autowired
    ReportService reportService;


    // 唯一的图片处理的方法
    @RequestMapping("/upload")
    public ResponseResult<String> upload(@RequestParam(value ="headerImg") MultipartFile uploadFile){
        System.out.println(uploadFile.getOriginalFilename());
        String filename = uploadFile.getOriginalFilename();
        // 重新获取名字，保证不重复
        String subFix = filename.substring(filename.lastIndexOf("."));
        filename = "comic" + System.currentTimeMillis()+subFix;
        // E:/imgs/resource/id数字/comic2858292783742947.jpg
        File file = new File(imgReportPath+filename);

        System.out.println(imgReportPath+filename);
        if(!file.exists()){
            file.mkdirs();
            System.out.println(file.mkdirs());
        }

        ResponseResult<String> result = new ResponseResult<>();
        try {
            uploadFile.transferTo(file);
            result.setCode(200);
            result.setMsg("上传成功");
            result.setData(filename);
        } catch (IOException e) {
            e.printStackTrace();
            result.setCode(201);
            result.setMsg("上传失败");
        }
        return result;
    }


    @PostMapping("/add")
    public ResponseResult<Void> add(@RequestBody Report report){
        ResponseResult<Void> result = new ResponseResult<>();
        report.setStatus(0);
        report.setReportTime(new Date());
        System.out.println("举报对象是：："+report);
        try{
            int i = reportService.addReport(report);
            if(i != 0){
                result.setCode(200);
                result.setMsg("添加成功");
            }else {
                result.setCode(201);
                result.setMsg("添加失败");
            }
        }catch (Exception e){
            e.printStackTrace();
            result.setCode(201);
            result.setMsg("添加失败");
        }
        return  result;
    }

}
